package org.openwp3x.iclazz;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class AdGridAdapter extends BaseAdapter {

	private JSONArray list = new JSONArray();

	Activity activity;

	private static LayoutInflater inflater;

	public AdGridAdapter(final Activity activity) {
		this.activity = activity;
		AdGridAdapter.inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public void setList(final JSONArray list) {
		this.list = list;
	}

	public int getCount() {
		return this.list.length();
	}

	public Object getItem(final int position) {
		return null;
	}

	public long getItemId(final int position) {
		return 0;
	}

	public View getView(final int position, final View convertView, final ViewGroup parent) {
		View vi = convertView;
		ViewHolder holder;
		if (convertView == null) {
			vi = AdGridAdapter.inflater.inflate(R.layout.item_list, null);
			holder = new ViewHolder();
			holder.adDesc = (TextView) vi.findViewById(R.id.ad_desc);
			holder.publisherName = (TextView) vi.findViewById(R.id.ad_publisher);
			vi.setTag(holder);

		} else {
			holder = (ViewHolder) vi.getTag();
		}

		try {
			JSONObject jsonObject = this.list.getJSONObject(position);
			Long adId = jsonObject.getLong("id");
			String adDescription = jsonObject.getString("description");
			String adDate = getDate(jsonObject.getJSONObject("publicationDate").getString("$"));
			Long publisherId = jsonObject.getJSONObject("publisher").getLong("id");
			String publisherName = jsonObject.getJSONObject("publisher").getString("name");
			String publisherEmail = jsonObject.getJSONObject("publisher").getString("email");

			holder.adId = adId;
			holder.adDesc.setText(adDescription);
			holder.publisherId = publisherId;
			holder.publisherName.setText("Anunciado por " + publisherName + " em " + adDate);
			holder.publisherEmail = publisherEmail;

		} catch (Exception e) {
			holder.adDesc.setText(e.getMessage());
		}

		return vi;
	}

	private String getDate(final String dateToken) {
		try {
			String[] dateArray = dateToken.split(" ");
			dateArray = dateArray[0].split("-");
			return dateArray[2] + "/" + dateArray[1] + "/" + dateArray[0];
		} catch (Exception e) {
			return "";
		}

	}
}
